#pragma once
#include <iostream>
using namespace std;
#include "../netio.h"
#include "EventProecsser.h"

class TestHandler :
	public EventProecsser
{
public:
	TestHandler( void )
	{
		read_callback_.Set( this, &TestHandler::handle_read );
		write_callback_.Set( this, &TestHandler::handle_write );
		connect_callback_.Set( this, &TestHandler::handle_connect );
		accept_callback_.Set( this, &TestHandler::handle_accept );
	}
public:
	~TestHandler( void ) {};
	void handle_read( Socket &h, int errcode, int bytes, DataBlock *data_block, void *act )
	{
		string ip;
		short port;
		h.localaddr( ip, port );
		h.remoteaddr( ip, port );
		static int i = 0;
		printf( "%d\n", ++i);
		
		if( errcode )
		{
			delete data_block;
			NetIO::async_cancel( h );
			h.close();
			return;
		}
		

		string s( data_block->rd_ptr( ), data_block->length( ) );
		cout << s.c_str( ) <<endl;
		
	}
	void handle_write( Socket &h, int errcode, int bytes, DataBlock *data_block, void *act )
	{
		
		if( errcode )
		{
			delete data_block;
			NetIO::async_cancel( h );
			return;

		}
		 


		data_block->crunch( );
		NetIO::async_read( h, data_block, act );
	}
	void handle_connect( Socket &h, int errcode, void* )
	{
		if ( errcode )
		{
			NetIO::async_cancel( h );
			h.close();
		}
	}
	void handle_accept( Socket &h, int errcode, void* act )
	{
		if( errcode )
		{
			NetIO::async_cancel( h );
			return;
		}
		Singleton<Reactor>::instance()->register_handler( h );
		DataBlock *data_block = new DataBlock( 4096 );
		for ( int i = 0; i < 10000; i ++ )
			NetIO::async_read( h, data_block, act );
		Singleton<Reactor>::instance()->close( );
	//	Singleton<Acceptor>::instance()->async_accept( );
	}
};
